package org.extplus.test.dwrstore;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.extplus.base.Response;

public class UserService {
    private static Map<Integer, User> users;
    private static int count = 7;

    static void initData() {
        if (users == null) {
            users = new LinkedHashMap<Integer, User>();
            users.put(1, new User(1, "Fred", "Flintstone", "fred@flintstone.com"));
            users.put(2, new User(2, "Wilma", "Flintstone", "wilma@flintstone.com"));
            users.put(3, new User(3, "Pebbles", "Flintstone", "pebbles@flintstone.com"));
            users.put(4, new User(4, "Barney", "Rubble", "barney@rubble.com"));
            users.put(5, new User(5, "Betty", "Rubble", "betty@rubble.com"));
            users.put(6, new User(6, "BamBam", "Rubble", "bambam@rubble.com"));
        }
    }

    public static Response<User[]> read() {
        initData();
        Response<User[]> res = new Response<User[]>();
        res.setSuccess(true);
        res.setMessage("Loaded data");
        res.setData(users.values().toArray(new User[users.size()]));
        return res;
    }

    public static Response<User[]> create(User[] us) {
        initData();
        for (User user : us) {
            user.setId(count);
            users.put(count, user);
            count++;
        }

        Response<User[]> res = new Response<User[]>();
        res.setSuccess(true);
        res.setMessage("Created record");
        res.setData(us);
        return res;
    }

    public static Response<User[]> update(User[] us) {
        initData();

        List<User> upd = new ArrayList<User>();
        for (User user : us) {
            user = users.get(user.getId()).update(user);
            upd.add(user);
            users.put(user.getId(), user);
        }

        Response<User[]> res = new Response<User[]>();
        res.setSuccess(true);
        res.setMessage("Updated record");
        res.setData(upd.toArray(new User[upd.size()]));
        return res;
    }

    public static Response<User[]> remove(Integer[] ids) {
        initData();
        User[] destroy;
        destroy = new User[ids.length];
        for (int i = 0; i < ids.length; i++) {
            destroy[i] = users.get(ids[i]);
            users.remove(ids[i]);
        }

        Response<User[]> res = new Response<User[]>();
        res.setSuccess(true);
        res.setMessage("Destroyed record");
        res.setData(destroy);
        return res;
    }
}
